package com.develope.menu;

import java.util.ArrayList;

import org.ksoap2.serialization.PropertyInfo;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.develope.menu.service.HttpHandler;
import com.develope.menu.service.SoapHelper;
import com.develope.menu.utils.Alerts;
import com.develope.menu.utils.Logger;
import com.develope.menu.utils.Utils;

public class MainActivity extends Activity implements OnClickListener,
		OnItemClickListener {

	ArrayList<Men> arrMenu = new ArrayList<Men>();
	MyArrayAdapter adapter = null;
	ListView lvMon = null;
	EditText edtSluong;
	Button btnAdd, btnSend;
	ImageButton btnRemove;
	Spinner spinMon, spin;

	ArrayList<String> arrBan = new ArrayList<String>();
	ArrayAdapter<String> adapterBan;

	ArrayList<String> arrMon = new ArrayList<String>();
	ArrayAdapter<String> adapterMon;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		arrBan.add("SELECT DESK");
		arrMon.add("SELECT FOOD");

		// Get danh sach ban tu he thong

		PropertyInfo proInfo = new PropertyInfo();
		proInfo.setName("example");
		proInfo.setValue("example");
		proInfo.setType(String.class);
		HttpHandler httpHandlerDesk = new HttpHandler(SoapHelper.METHOD_ITEM, proInfo) {

			@Override
			public void onResponse(int errorCode, String result) {

				Alerts.hideLoadingDialog();
				// Logger.error("[onResponse] errorCode:" + errorCode);

				if (TextUtils.isEmpty(result) || !result.contains(";")) {
					Alerts.showErrorDialog(MainActivity.this,
							"Get information failed. Please try again.", null);
					return;
				}

				String[] s = result.split(";");
				for (int k = 0; k < s.length; k++) {
					arrMon.add(s[k]);
				}

			}
		};

		if (Utils.isEnableNetwork(this, true)) {
			// show progress dialog
			Alerts.showLoadingDialog(this, null, null);
			httpHandlerDesk.execute();

		}

		// lay danh sach mon tu he thong

		HttpHandler httpHandlerItem = new HttpHandler(SoapHelper.METHOD_DESK,  proInfo) {

			@Override
			public void onResponse(int errorCode, String result) {

				Alerts.hideLoadingDialog();
				// Logger.error("[onResponse] errorCode:" + errorCode);

				if (TextUtils.isEmpty(result) || !result.contains(";")) {
					Alerts.showErrorDialog(MainActivity.this,
							"Get user information failed. Please try again.",
							null);
					return;
				}

				String[] s = result.split(";");
				for (int k = 0; k < s.length; k++) {
					arrBan.add(s[k]);
				}

			}
		};

		if (Utils.isEnableNetwork(this, true)) {
			// show progress dialog
			Alerts.showLoadingDialog(this, null, null);
			httpHandlerItem.execute();
		}

		// Gan cac doi tuong vao ten bien
		btnAdd = (Button) findViewById(R.id.btnAdd);
		btnSend = (Button) findViewById(R.id.btnSend);
		btnRemove = (ImageButton) findViewById(R.id.btnDelete);
		edtSluong = (EditText) findViewById(R.id.edtSluong);

		// Gan gia tri lay ve tu he thong vao spinner

		spin = (Spinner) findViewById(R.id.spinner1);
		adapterBan = new ArrayAdapter<>(this,
				android.R.layout.simple_spinner_item, arrBan);
		adapterBan
				.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		spin.setAdapter(adapterBan);
		spin.setSelection(0);
		spin.setOnItemSelectedListener(new MyProcessEvent());

		spinMon = (Spinner) findViewById(R.id.spinner2);
		adapterMon = new ArrayAdapter<>(this,
				android.R.layout.simple_spinner_item, arrMon);
		adapterMon
				.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		spinMon.setAdapter(adapterMon);
		spinMon.setSelection(0);
		spinMon.setOnItemSelectedListener(new MyProcessEvent());

		lvMon = (ListView) findViewById(R.id.lvMon);
		adapter = new MyArrayAdapter(this, R.layout.my_item_layout, arrMenu);
		lvMon.setAdapter(adapter);
		lvMon.setOnItemClickListener(this);
		lvMon.setEnabled(true);

		btnAdd.setOnClickListener(this);
		btnSend.setOnClickListener(this);
		btnRemove.setOnClickListener(this);

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Toast.makeText(this, "item " + arg2, 0).show();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private class MyProcessEvent implements OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {

		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.btnAdd:
			add();
			break;

		case R.id.btnSend:
			send();
			break;

		case R.id.btnDelete:
			delete();
			break;
		default:
			break;
		}
	}

	private void add() {
		// TODO Auto-generated method stub
		boolean cancel = false;
		View focusView = null;
		
		String mon = spinMon.getSelectedItem().toString() + "";
		String sluong = edtSluong.getText().toString();
		String ban = spin.getSelectedItem().toString() + "";
		String user = getIntent().getStringExtra(LoginActivity.EXTRA_MESSAGE);
		
		String text1 = "Vui lòng chọn bàn";
		String text2 = "Vui lòng chọn món ăn";
		String text3 = "Vui lòng nhập số lượng";

		if (spin.getSelectedItemPosition() == 0) {
			Toast.makeText(this, text1, 1).show();
			focusView = spin;
			focusView.requestFocus();
		} else {
			if (spinMon.getSelectedItemPosition() == 0) {
				Toast.makeText(this, text2, 1).show();
				spinMon.requestFocus(0);
				
			} else {
				if (TextUtils.isEmpty(sluong)) {
					Toast.makeText(this, text3, 1).show();
					edtSluong.requestFocus();
				} else {
					Men men = new Men();

					men.setBan(ban);
					men.setMon(mon);
					men.setSluong(Integer.parseInt(sluong));
					men.setUser(user);

					arrMenu.add(men);
					adapter.notifyDataSetChanged();

					spinMon.setFocusable(true);
					spin.setSelected(true);
					spinMon.setSelection(0);	
					edtSluong.setText(null);
					BaseApplication.hideKeyboard(MainActivity.this, lvMon);
				}
			}
		}
	}

	private void delete() {
		// TODO Auto-generated method stub
		for (int i = lvMon.getChildCount() - 1; i >= 0; i--) {
			View v = lvMon.getChildAt(i);
			CheckBox chk = (CheckBox) v.findViewById(R.id.chkOk);
			if (chk.isChecked()) {
				arrMenu.remove(i);
			}
		}
		adapter.notifyDataSetChanged();
	}

	private void send() {
		// TODO Auto-generated method stub

		int i = lvMon.getChildCount();
		String value = "";
		for (int j = 0; j <= i - 1; j++) {
			value += arrMenu.get(j).toString() + ";";

		}

		String a= value;
		
		PropertyInfo proInfo = new PropertyInfo();
		proInfo.setName("item");
		proInfo.setValue(a);
		proInfo.setType(String.class);
		HttpHandler httpHandlerSetItem = new HttpHandler(
				SoapHelper.METHOD_SET_ITEM, proInfo) {

			@Override
			public void onResponse(int errorCode, String result) {

				Alerts.hideLoadingDialog();
				Logger.error("[onResponse] errorCode:" + errorCode);

				if (TextUtils.isEmpty(result)) {
					Alerts.showButtonDialog(MainActivity.this,
							"Get user information failed. Please try again.",
							null);
					return;
				}
				switch (result) {
				case "True":
					Alerts.showNotifyDialog(MainActivity.this,
							"Send Menu Success");
					deleteAll();
					return;
				case "False":
					Alerts.showNotifyDialog(MainActivity.this,
							"Send Menu Failed, Please try again");
					return;

				}

			}

			private void deleteAll() {
				// TODO Auto-generated method stub
				for (int i = lvMon.getChildCount() - 1; i >= 0; i--) {
					arrMenu.remove(i);
				}
				adapter.notifyDataSetChanged();
			}

		};

		if (Utils.isEnableNetwork(this, true)) {
			// show progress dialog
			Alerts.showLoadingDialog(this, null, null);
			httpHandlerSetItem.execute();

		}

	}

}
